<script setup>
import { ref, reactive, watch, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import SelectRecipientModal from '@/components/document/SelectRecipientModal.vue';
import { users as mockUsers } from '@/stores/mockData.js';
import { QuillEditor } from '@vueup/vue-quill';

// ========== Props ========== //
const props = defineProps({
  initialData: {
    type: Object,
    default: null
  }
});

// ========== Emits ========== //
const emit = defineEmits(['submit', 'cancel']);

// ========== 使用 mock 用户数据 ========== //
const users = mockUsers;

// ========== 表单数据 ========== //
const form = reactive({
  title: '',
  content: '' // 保存 HTML 内容
});

// ========== 接收人 ========== //
const selectedRecipients = ref([]);
const recipientModalRef = ref(null);

// ========== 附件 ========== //
const fileList = ref([]);

// ========== 是否为编辑模式 ========== //
const isEdit = ref(false);

// ========== 富文本编辑器工具栏配置 ========== //
const quillToolbar = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ 'header': 1 }, { 'header': 2 }],
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],
  [{ 'indent': '-1' }, { 'indent': '+1' }],
  [{ 'direction': 'rtl' }],
  [{ 'size': ['small', false, 'large', 'huge'] }],
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
  [{ 'color': [] }, { 'background': [] }],
  [{ 'font': [] }],
  [{ 'align': [] }],
  ['link', 'image', 'video'],
  ['clean']
];

// ========== 监听 initialData，用于回填数据 ========== //
watch(
    () => props.initialData,
    (val) => {
      if (val) {
        isEdit.value = true;
        form.title = val.title || '';
        form.content = val.content || ''; // 支持 HTML 内容

        if (Array.isArray(val.recipientIds) && val.recipientIds.length > 0) {
          const selectedUsers = users.filter(user => val.recipientIds.includes(user.id));
          selectedRecipients.value = selectedUsers;
        } else {
          selectedRecipients.value = [];
        }

        if (Array.isArray(val.attachments)) {
          fileList.value = val.attachments.map(file => ({
            name: file.name,
            size: file.size,
            type: file.type,
            raw: file.raw || null,
            url: file.url
          }));
        } else {
          fileList.value = [];
        }
      } else {
        isEdit.value = false;
        form.title = '';
        form.content = '';
        selectedRecipients.value = [];
        fileList.value = [];
      }
    },
    { immediate: true }
);

// ========== 打开接收人弹窗 ========== //
const openRecipientModal = () => {
  recipientModalRef.value?.openDialog();
};

// ========== 处理接收人选择 ========== //
const handleRecipientSelection = (selectedUserIds) => {
  const selectedUsers = users.filter(user => selectedUserIds.includes(user.id));
  selectedRecipients.value = selectedUsers;
};

// ========== 文件上传处理 ========== //
const handleFileChange = (file, fileList) => {
  const MAX_SIZE = 10 * 1024 * 1024; // 10MB
  if (file.size > MAX_SIZE) {
    ElMessage.error(`文件 ${file.name} 超过 10MB，无法上传`);
    fileList.value = fileList.filter(f => f.uid !== file.uid);
    return;
  }
  fileList.value = fileList;
};

// ========== 文件移除处理 ========== //
const handleRemoveFile = (file, currentFileList) => {
  fileList.value = currentFileList;
};

// ========== 提交表单 ========== //
const handleSubmit = () => {
  if (!form.title.trim()) {
    ElMessage.error('请输入标题');
    return;
  }
  if (!form.content.trim() || form.content === '<p><br></p>') {
    ElMessage.error('请输入内容');
    return;
  }
  if (selectedRecipients.value.length === 0) {
    ElMessage.error('请至少选择一位接收人');
    return;
  }

  const filesWithUrl = fileList.value.map(file => ({
    name: file.name,
    size: file.size,
    type: file.type,
    raw: file.raw,
    url: file.url || URL.createObjectURL(file.raw)
  }));

  const submitData = {
    title: form.title,
    content: form.content, // 保存为 HTML 字符串
    recipientIds: selectedRecipients.value.map(r => r.id),
    recipients: selectedRecipients.value,
    attachments: filesWithUrl
  };

  emit('submit', submitData);
};

// ========== 取消操作 ========== //
const handleCancel = () => {
  emit('cancel');
};
</script>

<template>
  <!-- 全屏遮罩 -->
  <div class="modal-mask" @click="handleCancel">
    <div class="modal" @click.stop>
      <!-- 标题栏 -->
      <div class="modal-title">
        {{ isEdit.value ? '编辑通知' : '新建通知' }}
        <span class="modal-close" @click="handleCancel">×</span>
      </div>

      <!-- 表单区域 -->
      <div class="modal-content">
        <el-form :model="form" label-width="120px">
          <!-- 标题 -->
          <el-form-item label="标题">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>

          <!-- 内容 - 富文本编辑器 -->
          <el-form-item label="内容">
            <div class="quill-wrapper">
              <QuillEditor
                  v-model:content="form.content"
                  contentType="html"
                  placeholder="请输入通知内容，支持加粗、斜体、列表、图片、链接等..."
                  :toolbar="quillToolbar"
                  theme="snow"
                  style="height: 400px;"
              />
            </div>
          </el-form-item>

          <!-- 接收人 -->
          <el-form-item label="接收人">
            <el-button type="primary" @click="openRecipientModal">选择接收人</el-button>

            <!-- 状态提示 -->
            <div class="recipient-status" :class="{ 'has-selection': selectedRecipients.length > 0 }">
              {{ selectedRecipients.length > 0 ? `已选择 ${selectedRecipients.length} 人` : '尚未选择接收人' }}
            </div>

            <!-- 已选择的接收人列表 -->
            <div v-if="selectedRecipients.length > 0" class="selected-recipients">
              <el-tag
                  v-for="user in selectedRecipients"
                  :key="user.id"
                  size="small"
                  style="margin-right: 6px; margin-bottom: 4px;"
              >
                {{ user.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 附件 -->
          <el-form-item label="附件">
            <el-upload
                action="#"
                :on-change="handleFileChange"
                :file-list="fileList.value"
                :auto-upload="false"
                :multiple="true"
                :on-remove="handleRemoveFile"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">支持多文件上传</div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="action-footer">
            <el-button type="primary" @click="handleSubmit">
              {{ isEdit.value ? '保存修改' : '保存为草稿' }}
            </el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>

        <!-- 接收人选择弹窗 -->
        <SelectRecipientModal
            ref="recipientModalRef"
            :selected-user-ids="selectedRecipients.map(u => u.id)"
            @confirm-selection="handleRecipientSelection"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全屏遮罩 */
.modal-mask {
  position: fixed;
  z-index: 9999;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.18);
  display: flex;
  align-items: stretch;
  justify-content: stretch;
}

/* 模态框：全屏 */
.modal {
  background: #fff;
  width: 100vw;
  height: 100vh;
  min-width: 0;
  min-height: 0;
  max-width: none;
  max-height: none;
  box-shadow: none;
  padding: 0;
  display: flex;
  flex-direction: column;
}

/* 标题栏：渐变背景 + 白色文字 */
.modal-title {
  font-size: 1.5rem;
  font-weight: bold;
  padding: 24px 36px 16px 36px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #234d78 0%, #6c7986 100%);
  color: #fff;
}
.modal-close {
  color: #fff;
  font-size: 1.8rem;
  cursor: pointer;
}

/* 表单内容区域 */
.modal-content {
  flex: 1;
  padding: 24px 36px;
  overflow-y: auto;
  background: #f9f9fb;
}

/* 接收人状态提示 */
.recipient-status {
  margin-top: 8px;
  font-size: 14px;
  color: #999;
}
.recipient-status.has-selection {
  color: #409eff;
}

/* 已选择接收人列表 */
.selected-recipients {
  margin-top: 8px;
  min-height: 32px;
  padding: 4px 0;
}

/* 操作按钮区域 */
.action-footer {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 18px;
}

/* Element Plus 按钮样式覆盖 */
.action-footer .el-button--primary {
  background: #409eff;
  border-color: #409eff;
}
.action-footer .el-button--primary:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}
.action-footer .el-button:not(.el-button--primary) {
  background: #909399;
  border-color: #909399;
  color: #fff;
}
.action-footer .el-button:not(.el-button--primary):hover {
  background: #b1b1b1;
  border-color: #b1b1b1;
}

/* 修复 Quill 编辑器在 el-form-item 中的布局问题 */
.quill-wrapper {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
}

.quill-wrapper .ql-container {
  height: 400px;
}
</style>
